<template>
	<scroll-view class="container" scroll-y="true" show-scrollbar="false" lower-threshold="20"
		@scrolltolower="handleScroll">
		<view class="header-background" :class="{active: memberInfo.type === 2}">
			<view class="header-wrapper">
				<view class="left">
					<img class="avatar" :src="memberInfo.avatarUrl" alt="avatar" />
				</view>
				<view class="right">
					<view class="title-wrapper">
						<h1 style="font-weight: 500;">{{ memberInfo.name }}</h1>
						<view class="member-title advanced" v-if="memberInfo.type === 2" style="text-shadow: none;">
							高级管理员
						</view>
						<view class="member-title middle" v-else-if="memberInfo.type === 1" style="text-shadow: none;">
							中级管理员
						</view>
						<view class="member-title primary" v-else style="text-shadow: none;">
							初级管理员
						</view>
					</view>
					<view class="info-wrapper">
						<p>工号：<span>{{ memberInfo.account }}</span></p>
						<p>联系方式：<span>{{ memberInfo.tel }}</span></p>
					</view>
				</view>
			</view>
		</view>
		<view class="card">
			<view class="header">
				<span class="title">
					当前管理区域：
					<span class="area">
						{{ memberInfo.areas[0].name === undefined ? '暂无' : memberInfo.areas[0].name }}
					</span>
					<span v-if="memberInfo.areas[0].name !== '暂无'">&nbsp;&nbsp;等</span>
				</span>
				<button v-show="currentUser !== memberInfo.account && memberInfo.type !== 2" class="change-right"
					@click="handleModify">修改权限</button>
			</view>
			<DeviceCard v-for="(item, index) in currentDeviceList" :key="index" :id="item.id" :code="item.code"
				:status="item.status" :picUrl="item.image" :area="item.area">
			</DeviceCard>
		</view>
	</scroll-view>

	<!-- 使用 uni-popup 替代自定义弹窗 -->
	<uni-popup ref="modifyPopup" type="bottom" background-color="transparent">
		<view class="dialog-overlay" @click.self="closeDialog" @touchmove.stop.prevent>
			<view class="dialog" role="dialog" aria-modal="true" aria-labelledby="dialogTitle">
				<header class="dialog-header">
					<text id="dialogTitle">修改对象：{{ memberInfo.name }}</text>
					<button @click="closeDialog" class="close-btn" aria-label="关闭">✕</button>
				</header>

				<form @submit.prevent="submitChange" class="dialog-body">
					<div class="form-group">
						<label>修改时间</label>
						<input type="text" v-model.trim="modifyInfo.applyTime" disabled class="input-field" />
					</div>

					<div class="form-group">
						<label>目标工号</label>
						<input type="text" v-model.trim="modifyInfo.targetAccount" disabled class="input-field" />
					</div>

					<!-- <div class="form-group">
						<label>修改身份<span class="required">*</span></label>
						<picker :range="typeOptions" @change="onTypeChange">
							<view class="input-field">{{ modifyInfo.newType || '请选择身份类型' }}</view>
						</picker>
					</div> -->

					<div class="form-group">
						<label>授权区域<span class="required">*</span></label>
						<picker :range="areaList" range-key="area" @change="onAreaChange">
							<view class="input-field">
								{{ modifyInfo.newArea || '请选择授权区域' }}
							</view>
						</picker>
					</div>

					<div class="form-group">
						<label>您的联系电话</label>
						<input type="tel" v-model.trim="modifyInfo.yourTel" required class="input-field" />
					</div>

					<div class="form-group">
						<label>附言</label>
						<input type="text" v-model.trim="modifyInfo.yourComments" class="input-field" />
					</div>

					<footer class="dialog-footer">
						<button type="button" @click="closeDialog" class="cancel-btn">取消</button>
						<button type="button" @click="submitChange" class="submit-btn">确认修改</button>
					</footer>
				</form>
			</view>
		</view>
	</uni-popup>
</template>

<script>
	import DeviceCard from '/components/DeviceCard.vue';
	import formatDateTime from '@/utils/formatDateTime';
	import {
		getUserByAccount
	} from '@/api/user';
	import {
		getAtmById,
		getAtmsByUserId
	} from '@/api/atm';
	import {
		getAreas,
		getAreasByUserId,
		grantUserArea
	} from '@/api/area';

	export default {
		components: {
			DeviceCard
		},

		data() {
			return {
				memberInfo: {
					id: null,
					account: '',
					name: '',
					type: null,
					tel: '',
					avatarUrl: '',
					areas: []
				},

				modifyInfo: {
					applyTime: '',
					targetAccount: '',
					// newType: '',
					newArea: '',
					newAreaId: null,
					yourTel: '',
					yourComments: ''
				},

				count: 3,
				deviceList: [],
				areaList: [],
				// typeOptions: ['中级管理员', '初级管理员'],
				currentUser: '',
				currentDevice: '',
				currentTime: '',
			};
		},

		computed: {
			currentDeviceList() {
				return this.deviceList.slice(0, this.count);
			}
		},

		onLoad: async function(option) {
			await this.fetchData(option.account);
			this.currentUser = JSON.parse(uni.getStorageSync("userInfo")).account;
		},

		methods: {
			async fetchData(account) {
				// 获取用户数据
				const memberInfo = await getUserByAccount(account);
				this.memberInfo = {
					id: memberInfo.id,
					account: memberInfo.account,
					name: memberInfo.name,
					type: memberInfo.userRight,
					tel: memberInfo.tel,
					avatarUrl: memberInfo.avatarUrl
				}
				const areas = await getAreasByUserId(this.memberInfo.id);
				console.log(areas)
				this.memberInfo.areas = areas.data ? areas.data : [{
					id: null,
					name: '暂无'
				}];

				// 获取设备数据
				const deviceList = await getAtmsByUserId(this.memberInfo.id);
				console.log(deviceList);

				if (deviceList.data.length === 0) {
					uni.showToast({
						title: "用户无授权设备",
						icon: "error",
						duration: 2000
					});
				} else {
					this.deviceList = deviceList.data.map((d) => ({
						id: d.id,
						code: d.atmCode,
						status: d.status,
						stock: d.money,
						areaId: d.areaId,
						image: '/static/ATM_pic.png',
					}));
					const areasObj = {};
					areas.data.forEach(area => {
						areasObj[area.id] = area.name;
					})
					this.deviceList.forEach(d => {
						d.area = areasObj[d.areaId];
					});
				}

				// 获取区域数据
				const areaList = await getAreas();
				this.areaList = areaList.map(d => ({
					id: d.id,
					area: d.name,
				}));
			},

			// 滚动懒加载
			handleScroll() {
				const rest = this.deviceList.length - this.count;
				setTimeout(() => {
					this.count += rest >= 3 ? 3 : rest;
				}, 500);
			},

			// onTypeChange(e) {
			// 	this.modifyInfo.newType = this.typeOptions[e.detail.value];
			// },

			onAreaChange(e) {
				this.modifyInfo.newArea = this.areaList[e.detail.value].area;
				this.modifyInfo.newAreaId = this.areaList[e.detail.value].id;
			},

			handleModify() {
				this.$refs.modifyPopup.open();
				this.modifyInfo.applyTime = formatDateTime(new Date());
				this.modifyInfo.targetAccount = this.memberInfo.account;
			},

			closeDialog() {
				this.$refs.modifyPopup.close();
			},

			async submitChange() {
				console.log(this.modifyInfo);
				const userId = this.memberInfo.id;
				const areaId = this.modifyInfo.newAreaId;
				if (!areaId) {
					uni.showToast({
						title: "请选择授权区域",
						icon: "error",
						duration: 1500
					});
					return;
				}
				const result = await grantUserArea(userId, areaId);
				if (result.code === 200) {
					uni.showToast({
						title: "修改信息提交成功",
						icon: "success",
						duration: 2000
					});

					uni.redirectTo({
						url: `/pages/memberInfo/memberInfo?account=${this.memberInfo.account}`
					});

					this.$refs.modifyPopup.close();
					this.modifyInfo = {
						applyTime: '',
						targetAccount: '',
						newArea: '',
						newAreaId: null,
						yourTel: '',
						yourComments: ''
					};
				}
			}
		},
	}
</script>

<style lang="scss" scoped>
	.container {
		position: relative;
		width: 100vw;
		height: 95dvh;
		box-sizing: border-box;
	}

	.header-background {
		position: absolute;
		z-index: 1;
		padding: 44px 16px 0;
		height: 240px;
		width: 100vw;
		box-sizing: border-box;
		background-image: linear-gradient(#BD3124, #BD3124, #BD3124, #BD3124, #BD3124, #BD3124, #F5F5F5); // 渐变
	}

	.active {
		background-image: linear-gradient(#BD3124, #FBB03B, #EDD181, #F5F5F5); // 渐变
	}

	.header-wrapper {
		display: flex;
		padding: 0 12px;
	}

	.header-background .left {
		font-size: 24px;
		color: #FFF;
	}

	.header-background .right {
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		margin-left: 16px;
		font-size: 14px;
		color: #F5F5F5;
	}

	.avatar {
		display: block;
		width: 100px;
		height: 100px;
		border-radius: 8px;
		background-color: black;
	}

	.title-wrapper {
		display: flex;
		align-items: center;
		align-content: baseline;

	}

	.member-title {
		margin-left: 8px;
		width: 80px;
		height: 28px;
		border-radius: 8px;
		text-align: center;
		line-height: 28px;
		font-size: 12px;
	}

	.advanced {
		background-image: linear-gradient(to bottom right, #F4CE98, #FFFBC7, #FBB03B, #EDD181, #FFFBC7); // 渐变
		color: #A16222;
		font-style: italic;
		font-weight: 500;
	}

	.middle {
		background-color: rgb(154, 154, 154, 0.9);
		background-image: linear-gradient(to bottom right, #f5f5f5, #777, #555, #333333, #eeeeee);
		font-style: italic;
		font-weight: 500;
		color: #F5F5F5;
	}

	.primary {
		color: #F5F5F5;
		background-color: #666;
	}

	.card {
		position: absolute;
		top: 172px;
		left: 50%;
		transform: translateX(-50%);
		z-index: 2;

		padding: 20px 20px;
		width: 316px;
		min-height: 40px;
		border-radius: 12px;
		background-color: #FFF;
		// box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
	}

	.card .header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;
		padding-bottom: 16px;
		border-bottom: 1px dashed #BBB;
		font-size: 16px;
		color: #333;
	}

	.card .title .area {
		font-size: 20px;
		color: #333;
		font-family: 'Times New Roman', Times, serif;
		font-weight: 700;
	}

	.change-right {
		display: inline-block;
		margin: 0 0;
		font-size: 12px;
	}

	// 弹窗
	/* 弹窗样式 */
	.dialog-overlay {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.35);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 9999;
		backdrop-filter: blur(4px);
	}

	.dialog {
		background-color: #fff;
		width: 100%;
		max-width: 360px;
		border-radius: 16px;
		box-shadow: 0 12px 24px rgba(0, 0, 0, 0.2);
		display: flex;
		flex-direction: column;
		overflow: hidden;
		animation: fadeInScale 0.5s ease forwards;
	}

	@keyframes fadeInScale {
		0% {
			opacity: 0;
			transform: scale(0.95);
			transform: rotate(0deg);
		}

		50% {
			opacity: 0;
			transform: scale(2);
			transform: rotate(360deg);
		}

		100% {
			opacity: 1;
			transform: scale(1);
			transform: rotate(0deg);
		}
	}

	.dialog-header {
		padding: 18px 22px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-weight: 700;
		font-size: 20px;
		color: #BD3124;
		border-bottom: 1px solid #eee;
	}

	.close-btn {
		margin: 0 0;
		background: none;
		border: none;
		font-size: 24px;
		cursor: pointer;
		color: #999;
		transition: color 0.3s;
		line-height: 1;
		padding: 0;
	}

	.close-btn::after {
		display: none;
	}

	.close-btn:hover {
		color: #BD3124;
	}

	.dialog-body {
		padding: 20px 25px;
		max-height: 70vh;
		overflow-y: auto;
		font-size: 15px;
		color: #333;
	}

	.form-group {
		display: flex;
		flex-direction: column;
		margin-bottom: 18px;
	}

	.form-group label,
	fieldset legend {
		font-weight: 600;
		margin-bottom: 8px;
		color: #555;
		user-select: none;
	}

	.required {
		color: #BD3124;
		margin-left: 3px;
	}

	.input-field {
		padding: 10px 14px;
		border-radius: 8px;
		border: 1.8px solid #ccc;
		font-size: 15px;
		transition: border-color 0.3s;
	}

	.input-field:focus {
		outline: none;
		border-color: #BD3124;
		box-shadow: 0 0 8px rgba(189, 49, 36, 0.3);
	}

	.fault-types {
		display: flex;
		flex-wrap: wrap;
		gap: 12px;
	}

	.fault-types label {
		font-size: 14px;
		cursor: pointer;
		user-select: none;
		padding-left: 6px;
		position: relative;
	}

	.fault-types input[type="checkbox"] {
		width: 18px;
		height: 18px;
		margin-right: 6px;
		vertical-align: middle;
		cursor: pointer;
		accent-color: #BD3124;
	}

	.dialog-footer {
		display: flex;
		justify-content: space-between;
		padding: 20px 25px;
	}

	.cancel-btn,
	.submit-btn {
		flex: 1;
		margin: 0 5px;
		padding: 12px 0;
		border-radius: 25px;
		font-size: 16px;
		cursor: pointer;
		border: none;
		user-select: none;
		transition: background-color 0.3s ease;
	}

	.cancel-btn {
		color: #333;
		border: 0.5px solid #333;
		background-color: #FFF;
	}

	.submit-btn {
		background-color: #BD3124;
		color: #fff;
		font-weight: 700;
		box-shadow: 0 4px 12px rgba(189, 49, 36, 0.6);
	}

	.submit-btn:hover {
		background-color: #a42820;
		box-shadow: 0 6px 16px rgba(164, 40, 32, 0.8);
	}

	/* 滚动条优化 */
	.dialog-body::-webkit-scrollbar {
		width: 8px;
	}

	.dialog-body::-webkit-scrollbar-thumb {
		background-color: rgba(189, 49, 36, 0.3);
		border-radius: 4px;
	}

	.repair-success-banner {
		position: fixed;
		top: 120rpx;
		left: 50%;
		transform: translateX(-50%);
		background-color: #e6f7e6;
		color: #389e0d;
		padding: 20rpx 40rpx;
		border-radius: 12rpx;
		font-size: 28rpx;
		z-index: 9999;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	}


	/* 淡入淡出动画 */
	@keyframes fadeInOut {
		0% {
			opacity: 0;
			transform: translate(-50%, -10px);
		}

		10%,
		90% {
			opacity: 1;
			transform: translate(-50%, 0);
		}

		100% {
			opacity: 0;
			transform: translate(-50%, -10px);
		}
	}
</style>